using System;
using System.Collections.Generic;
using Ewk.MachineLearning.Classification.Interfaces;

namespace Ewk.MachineLearning.Classification.Common
{
    public class Comparer<T> : IComparer<T>, IEqualityComparer<T>
        where T:IEntity
    {
        private readonly Func<T, T, int> _compareFunction;
        private readonly Func<T, int> _hasCodeFunction;

        public Comparer(Func<T, T, int> compareFunction, Func<T, int> hasCodeFunction)
        {
            _compareFunction = compareFunction;
            _hasCodeFunction = hasCodeFunction;
        }

        public bool Equals(T x, T y)
        {
            return Compare(x, y) == 0;
        }

        public int GetHashCode(T x)
        {
            return x.Equals(default(T))
                       ? 0
                       : _hasCodeFunction(x);
        }

        public int Compare(T x, T y)
        {
            if (x.Equals(default(T)) || y.Equals(default(T)))
            {
                if (x.Equals(default(T)) && y.Equals(default(T)))
                {
                    return 0;
                }

                if (x.Equals(default(T)))
                {
                    return -1;
                }

                return 1;
            }

            return _compareFunction(x, y);
        }
    }
}